package com.second.rbm;

import com.rabbitmq.client.Channel;
import com.second.consts.OrderStatus;
import com.second.mapper.FGoodsMapper;
import com.second.mapper.FOrdSeckillMapper;
import com.second.mapper.IFOrdMapper;
import com.second.model.pojo.FGoods;
import com.second.model.pojo.FOrd;
import com.second.model.pojo.FOrdSeckill;
import com.second.service.IFOrdService;
import com.second.task.OrdTask;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import com.second.consts.RabbitConst;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
public class SeckillRbmService {

    @Autowired
    private IFOrdService ordService;

    @Autowired
    private FGoodsMapper goodsMapper;

    @Autowired
    private FOrdSeckillMapper ordSeckillMapper;

    @Autowired
    private OrdTask ordTask;

    //处理秒杀成功的消息 生成订单
    @RabbitHandler
    @RabbitListener(queues = RabbitConst.ORD_SEC_QUEUE)
    public void handler(Map<String, Object> args, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) Long tag) throws IOException {
        String userId = (String) args.get("userId");
        Integer secId = (Integer) args.get("secId");
        //保存订单
        Optional<FOrdSeckill> seckill = ordSeckillMapper.findById(secId);
        FGoods goods = goodsMapper.getById(seckill.get().getGoodsId());
        FOrd ord = ordService.save(seckill.get().getPrice(),Integer.valueOf(userId),goods.getShopId(),goods.getId());

        Map<String, Object> ordArgs = new HashMap<>();
        //重要的消息 - 订单的编号...
        ordArgs.put("ordNo", ord.getOrdCode());

        //异步调用发送到rabbitmq
        ordTask.sendOrdToRbm(ordArgs);
        //更新库存。。。
        ordSeckillMapper.updateNum(secId);
        channel.basicAck(tag, false);
    }

}
